/**
 * 
 */
package com.lanswon.service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.lanswon.common.enums.MessageType;
import com.lanswon.common.util.ImageUtil;
import com.lanswon.common.util.PropertiesUtils;
import com.lanswon.common.util.StringUtil;
import com.lanswon.dao.ImageMapper;
import com.lanswon.entity.ImageVO;
import com.lanswon.entity.UserVO;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @author lanswon
 *
 */
@Service
public class ImageService {

	@Autowired
	private ImageMapper imageMapper;

	public Map<String, Object> save(String imgType, String imgUrl, MultipartFile file) {
		Map<String, Object> dataMap = new HashMap() ;
		String imgName = file.getOriginalFilename();
		ImageVO imageVO = new ImageVO();

		if (file.getSize() == 0 ) {
			dataMap.put("code", 1);
			dataMap.put("message", MessageType.MT_TP_3);
			return dataMap;
		}
		if (!isFileName(imgName)) {
			dataMap.put("code", 1);
			dataMap.put("message", MessageType.MT_TP_1);
			return dataMap;
		}
		
		try {
			imageVO =imageMapper.getImgByName(imgName);
			byte[] imgItem = ImageUtil.imageToByte(file);
			
			if(imageVO==null) {	
				imageVO =new ImageVO();
				imageVO.setImgItem(imgItem);
				imageVO.setImgName(imgName);
				imageVO.setImgType(imgType);
				imageVO.setImgUrl(imgUrl);
				imageMapper.insert(imageVO);
			}else {
				imageVO.setImgItem(imgItem);
				imageMapper.updateByPrimaryKeySelective(imageVO);
			}

			updateOrLoad(file, imgName);
			dataMap.put("code", 0);
		} catch (IOException e) {
			dataMap.put("code", 1);
			dataMap.put("message", MessageType.MT_TP_2);
			e.printStackTrace();
		}
		return dataMap;
	}

	public byte[] getImgByName(String imgName) {

		return imageMapper.getImgByName(imgName).getImgItem();
	}

	public ImageVO getMessage(Long imgId) {
		return imageMapper.selectByPrimaryKey(imgId);
	}

	public Map<String, Object> update(Long imgId, MultipartFile file, String imgName) {
		Map<String, Object> dataMap = new HashMap();
		if (file.getSize() == 0) {
			dataMap.put("code", 1);
			dataMap.put("message", MessageType.MT_TP_3);
			return dataMap;
		}
		if (!isFileName(imgName)) {
			dataMap.put("code", 1);
			dataMap.put("message", MessageType.MT_TP_1);
			return dataMap;
		}
		try {
			byte[] imgItem = ImageUtil.imageToByte(file);
			ImageVO imageVO = new ImageVO();
			imageVO.setImgId(imgId);
			imageVO.setImgItem(imgItem);
			imageMapper.updateByPrimaryKeySelective(imageVO);
			updateOrLoad(file, imgName);
			dataMap.put("code", 0);
		} catch (IOException e) {
			dataMap.put("code", 1);
			dataMap.put("message", MessageType.MT_TP_2);
			e.printStackTrace();
		}
		return dataMap;
	}

	/**
	 * @param imgName
	 * @return
	 */
	private boolean isFileName(String imgName) {
		String fileType = imgName.substring(imgName.lastIndexOf(".") + 1, imgName.length());
		if (("png/jpg").indexOf(fileType) == -1) {
			return false;
		}
		return true;
	}

	public Map<String, Object> getImg(Long imgId) {
		ImageVO imageVO = imageMapper.selectByPrimaryKey(imgId);
		Map<String, Object> dataMap = new HashMap<String, Object>();
		Map<String, String> textMap = new HashMap<String, String>();
		Map<String, String> imgMap = new HashMap<String, String>();
		if (imageVO != null) {
			textMap.put("图片id", imageVO.getImgId().toString());
			textMap.put("图片名", imageVO.getImgName());

			imgMap.put("图片", imageVO.getImgUrl() + imageVO.getImgName());
		}
		dataMap.put("text", textMap);
		dataMap.put("textMap", "disabled");
		dataMap.put("img", imgMap);
		return dataMap;
	}

	public JSONObject load(Integer page, Integer limit, String type, String content) {

		if (page == null) {
			page = 1;
		}
		int pageindex = (page - 1) * limit;

		List<ImageVO> imageVOs = new ArrayList<ImageVO>();
		int count;
		if (!StringUtil.isEmpty(type) && !StringUtil.isEmpty(content)) {
			imageVOs = imageMapper.loadByCondition(pageindex, limit, type, content);
			count = imageMapper.countByCondition(type, content);
		} else {
			imageVOs = imageMapper.load(pageindex, limit);
			count = imageMapper.count();
		}
		// 处理数据
		JSONArray jsonArray = new JSONArray();
		for (ImageVO imageVO : imageVOs) {
			Map map = new HashMap();
			map.put("imgId", imageVO.getImgId());
			map.put("imgName", imageVO.getImgName());
			map.put("imaType", imageVO.getImgType());
			map.put("imgUrl", imageVO.getImgUrl());
			JSONObject json = JSONObject.fromObject(map);
			jsonArray.add(json);
		}
		// 组装数据
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("code", 0);
		jsonObject.put("msg", "");
		jsonObject.put("count", count);
		jsonObject.put("data", jsonArray);

		return jsonObject;
	}

	/**
	 * @param file
	 * @throws FileNotFoundException
	 */
	public void updateOrLoad(MultipartFile multfile, String imgName) {
		CommonsMultipartFile cf = (CommonsMultipartFile) multfile;

		PropertiesUtils.load("/config/system.properties");
		String localhost = System.getProperty("catalina.home") + PropertiesUtils.get("tomcat")
				+ PropertiesUtils.get("img");
		File file = new File(localhost + "\\" + imgName);

		file.getParentFile().mkdir();
		if (!file.exists()) {
			// 先得到文件的上级目录，并创建上级目录，在创建文件
			file.getParentFile().mkdir();
			try {
				// 创建文件
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		byte[] bytes = new byte[1024];
		OutputStream out;
		try {
			InputStream in = multfile.getInputStream();
			out = new FileOutputStream(file);
			while (in.read(bytes) != -1) {
				out.write(bytes);
			}
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
